package cn.hua.trip.admin.controller;

import cn.hua.trip.base.domain.Region;
import cn.hua.trip.base.query.QueryObject;
import cn.hua.trip.base.query.RegionQueryObject;
import cn.hua.trip.base.service.IRegionService;
import cn.hua.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/region")
public class RegionController {
    @Autowired
    private IRegionService regionService;


    @GetMapping
    @RequestMapping("/list")
    public String list(Model model){
        return "/region/list";
    }



    @RequestMapping("/listRegionByParentId")
    @ResponseBody
    public Object list(Long parentId){
        //查询出顶级地区菜单
        List<Region> list = regionService.selectByParentId(parentId);

        //将顶级菜单转换成页面能识别的treeview节点数据
        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();

        //转换过程: List<Region>    ---->   List<Map<String,Object>>
        for (Region region : list) {
            mapList.add(region.toMap());
        }
       return mapList;
    }


    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Region region){
        JSONResult result = new JSONResult();
        try {
            regionService.saveOrUpdate(region);
        }catch (Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
}
